/*
 * auth_sesstion.cpp
 *
 *  Created on: Dec 12, 2013
 *      Author: killerg
 */

#include "logon_deps.h"
#include "auth_session.h"
#include "logon.h"
#include "logon_cfg.h"

#include "share/connection_mgr.h"
#include "share/la_msg.pb.h"
#include "share/cl_msg.pb.h"
#include "share/msg.h"
#include "share/net_s.h"
#include "share/console2.h"

void handle_aresponse(la::AMsg* msg) {
	--g_logon.authsess->authing;

    auto &response = msg->response();
    auto sess = g_logon.clisess_mgr->base::connmgr.map_id.get(response.sessid());
    if (NULL == sess)
        return;

    int64_t playerid = response.playerid();
    if (response.has_data()) {
        CREATE_CL_LMSG(LAuth, auth);
        auth->set_json(response.data());
        sess->send_msg(___msg);
        if (response.has_playerid()) {
            sess->playerid = response.playerid();
            if (response.has_account())
                sess->account = response.account();
            if (response.has_mc())
            	sess->mc = response.mc();

            sess->stage = ELAuthed;
        } else {
            sess->stage = ELAuthing;
        }
    } else {
        sess->_trans->disconnect();
    }
}


bool auth_session_t::init() {
    bool ok = base::init(
    		fmt_cstr("%s:%d", g_cfg->AuthIp.c_str(), g_cfg->AuthPort),
    		[this](){
    			authing = 0;
    		},
    		NULL,
    		false
    		);

    UTIL_LOG(I, "auth at %s:%d", g_cfg->AuthIp.c_str(), g_cfg->AuthPort);

    ok = ok && base::reg(la::ID_AResponse, handle_aresponse);

    return ok;
}


void auth_session_t::post_auth(int64_t sessid, const std::string &data, co::EPlatformId epid) {
	if (!base::tran.is_connected()) {
		UTIL_LOG(I, "auth_session disconnected while post_auth");
		return;
	}

	++authing;

    CREATE_LA_LMSG(LRequest, request);
    request->set_sessid(sessid);
    request->set_data(data);
    request->set_epid(epid);
    base::tran.send(___msg);
}


